import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  // 一级路由
  { path: '/login', component: () => import('@/views/Login') },
  {
    path: '/',
    redirect: '/dashboard' /* 重定向配置页面 */,
    component: () => import('@/views/Home'),
    children: [
      /* 二级路由 */
      { path: 'dashboard', component: () => import('@/views/Home/Dashboard') },
      { path: 'user', component: () => import('@/views/Home/User') },
      { path: 'category', component: () => import('@/views/Home/Category') },
      { path: 'article', component: () => import('@/views/Home/Article') },
      {
        path: 'article/add',
        component: () => import('@/views/Home/Article/Editor'),
      },
      { path: 'messages', component: () => import('@/views/Home/Messages') },
    ],
  },
  { path: '*', component: () => import('@/views/404') } /* 404页面设置 */,
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
})

//设置全局前置导航守卫
router.beforeEach((to, from, next) => {
  //   // to: 需要访问的path
  //   // from: 从哪里来
  //   // next: 放行
  if (to.path === '/login') {
    return next()
  } else {
    let isToken = localStorage.getItem('token')
    //console.log(isToken)
    if (!isToken) {
      alert('请先登录!')
      return next('/login')
    } else {
      next()
    }
  }
})

export default router
